home *** CD-ROM | disk | FTP | other *** search
/ C & C++ Multimedia Cyber Classroom / C and C++ Multimedia Cyber Classroom (Prentice Hall) (1998).iso / src / fig20_42.jar / Ch20 / Fig20_42 / fig20_42.cpp
C/C++ Source or Header  |  1997-11-12  |  2KB  |  49 lines

  1. // Fig. 20.42: fig20_42.cpp
  2. // Demonstrating function objects.
  3. #include <iostream>
  4. #include <vector>
  5. #include <algorithm>
  6. #include <numeric>
  7. #include <functional>
  8.  
  9. using namespace std;
  10.  
  11. // binary function adds the square of its second argument and
  12. // the running total in its first argument and 
  13. // returns the sum
  14. int sumSquares( int total, int value ) 
  15.    { return total + value * value; }
  16.  
  17. // binary function class template which defines an overloaded 
  18. // operator() that function adds the square of its second 
  19. // argument and the running total in its first argument and 
  20. // returns the sum
  21. template< class T > 
  22. class SumSquaresClass : public binary_function< T, T, T >
  23. {
  24. public:
  25.    const T &operator()( const T &total, const T &value )
  26.       { return total + value * value; }
  27. };
  28.  
  29. int main()
  30. {
  31.    const int SIZE = 10;
  32.    int a1[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
  33.    vector< int > v( a1, a1 + SIZE );
  34.    ostream_iterator< int > output( cout, " " );
  35.    int result = 0;
  36.  
  37.    cout << "vector v contains:\n";
  38.    copy( v.begin(), v.end(), output );
  39.    result = accumulate( v.begin(), v.end(), 0, sumSquares );
  40.    cout << "\n\nSum of squares of elements in vector v using "
  41.         << "binary\nfunction sumSquares: " << result;
  42.  
  43.    result = accumulate( v.begin(), v.end(), 0, 
  44.                         SumSquaresClass< int >() );
  45.    cout << "\n\nSum of squares of elements in vector v using "
  46.         << "binary\nfunction object of type " 
  47.         << "SumSquaresClass< int >: " << result << endl;
  48.    return 0;
  49. }